function isHidden(el) {
  return el.offsetParent === null;
}

export function getOffset(el) {
  const rect = el.getBoundingClientRect();
  return {
    top: rect.top + window.pageYOffset,
    left: rect.left + window.pageXOffset,
  };
}

export function getStyle(el, prop) {
  return typeof getComputedStyle !== 'undefined' ? getComputedStyle(el, null).getPropertyValue(prop) : el.style[prop];
}


export function getScrollParent(el) {
  if (!(el instanceof HTMLElement)) {
    return window;
  }

  let parent = el;
  while (parent) {
    if (parent === document.body || parent === document.documentElement) {
      break;
    }

    if (!parent.parentNode) {
      break;
    }

    const overflow = getStyle(parent, 'overflow') + getStyle(parent, 'overflow-y') + getStyle(parent, 'overflow-x');

    if (/(scroll|auto)/.test(overflow)) {
      return parent;
    }

    parent = parent.parentNode;
  }

  return window;
}

export function inViewport(el, container, customOffset) {
  if (isHidden(el)) {
    return false;
  }

  const containerOffset = getOffset(container);
  let { top, left } = containerOffset;
  let bottom;
  let right;
  if (typeof container === 'undefined' || container === window) {
    top = window.pageYOffset;
    left = window.pageXOffset;
    bottom = top + window.innerHeight;
    right = left + window.innerWidth;
  } else {
    bottom = top + container.offsetHeight;
    right = left + container.offsetWidth;
  }

  const elementOffset = getOffset(el);

  return (
    top < elementOffset.top + customOffset.bottom + el.offsetHeight &&
    bottom > elementOffset.top - customOffset.top &&
    left < elementOffset.left + customOffset.right + el.offsetWidth &&
    right > elementOffset.left - customOffset.left
  );
}

export function keepLastIndex(obj) {
  if (window.getSelection) { // ie11 10 9 ff safari
    obj.focus(); // 解决ff不获取焦点无法定位问题
    const range = window.getSelection(); // 创建range
    range.selectAllChildren(obj); // range 选择obj下所有子内容
    range.collapseToEnd(); // 光标移至最后
  } else if (document.selection) { // ie10 9 8 7 6 5
    const range = document.selection.createRange(); // 创建选择对象
    range.moveToElementText(obj); // range定位到obj
    range.collapse(false); // 光标移至最后
    range.select();
  }
}
